package com.zxw.auth.config.security;

import com.zxw.auth.security.CustomerUserDetails;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.oauth2.common.DefaultOAuth2AccessToken;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.security.oauth2.provider.OAuth2Authentication;
import org.springframework.security.oauth2.provider.token.TokenEnhancer;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

/**
 * @author admin
 * @version 1.0
 * @description: 认证成功后添加拓展信息
 * @date 2022/5/27 16:24
 */
@Component
@Slf4j
public class JwtTokenEnhancer implements TokenEnhancer {

    @Override
    public OAuth2AccessToken enhance(OAuth2AccessToken oAuth2AccessToken, OAuth2Authentication oAuth2Authentication) {
        return oAuth2AccessToken;
    }

    /**
     * 扩展信息
     * TODO 刷新令牌的时候获取到的Principal为登陆用户名，这里需要判断区分是"获取令牌"还是"刷新token"
     *
     * @param oAuth2AccessToken
     * @param oAuth2Authentication
     */
    public void extendData(OAuth2AccessToken oAuth2AccessToken, OAuth2Authentication oAuth2Authentication) {
        Map<String, Object> map = new HashMap<>();
        CustomerUserDetails customerUserDetails = (CustomerUserDetails) oAuth2Authentication.getPrincipal();
        map.put("userId", customerUserDetails.getUserVO().getId());
        map.put("userName", customerUserDetails.getUserVO().getUserName());
        map.put("nickName", customerUserDetails.getUserVO().getNickName());
        map.put("phone", customerUserDetails.getUserVO().getPhone());
        map.put("email", customerUserDetails.getUserVO().getEmail());
        map.put("enabled", customerUserDetails.getUserVO().getEnabled());
        map.put("isActive", customerUserDetails.getUserVO().getIsActive());
        ((DefaultOAuth2AccessToken) oAuth2AccessToken).setAdditionalInformation(map);
    }

}
